<template>
  <el-dialog
    title="设置菜单权限"
    :close-on-click-modal="false"
    class="abow_dialog"
    width="40%"
    :visible.sync="visible"
  >
    <el-tree
      ref="menuTree"
      v-model="dataForm.Menus"
      :data="menuList"
      show-checkbox
      node-key="Id"
      :props="defaultProps"
    />
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
      <el-button size="mini" type="primary" @click="dataFormSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { treeDataTranslate } from '@/utils'
import { assignMenu, fetchList } from '@/api/menu'
import { getAllMenus } from '@/api/role'
export default {
  data() {
    return {
      visible: false,
      menuList: [],
      dataForm: {
        RoleId: 0,
        Menus: []
      },
      defaultProps: {
        children: 'children',
        label: 'Name'
      }
    }
  },
  methods: {
    init(id, code) {
      this.visible = true
      this.dataForm.RoleId = id
      this.dataForm.Code = code
      this.dataListLoading = true
      fetchList({}).then(({ data }) => {
        this.menuList = treeDataTranslate(data, 'Id')
        getAllMenus(code).then(({ data }) => {
          this.$refs.menuTree.setCheckedNodes(data)
        })
      }).catch((error) => {
        console.log(error)
      })
    },
    dataFormSubmit() {
      const ids = []
      const nodes = this.$refs.menuTree.getCheckedNodes(false, true)
      nodes.forEach((value, index) => {
        ids.push(value.Id)
      })
      var data = {
        'RoleId': this.dataForm.RoleId || undefined,
        'Menus': ids
      }
      var permission
      permission = assignMenu(data)
      permission.then((data) => {
        if (data && data.code === '20000') {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      })
    }
  }
}
</script>
